from typing import Optional

from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
import time
from summarizer import AbstractSummarizer
import codecs
import csv
import random

app = FastAPI()
news = []

origins = [
    "http://localhost",
    "http://localhost:8080"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# prepare news
with codecs.open('./news_summary/news_summs_validation.csv', 'r','utf-8', errors='ignore') as f:
    reader = csv.reader(f)
    news = [row[1] for row in reader]

class Text(BaseModel):
    content: str


@app.get("/")
def read_root():
    return {"Hello": "World"}


@app.get("/texts/random")
def get_texts():
    text = str(random.choice(news))
    return {
        "content": text
    }

@app.post("/texts/summarize")
def summarize_text(text: Text):
    summarizer = AbstractSummarizer()
    text = [text.content]
    result = summarizer.get_summary(text)[0]
    result = result.replace("<q>",". ").capitalize()
    return {"abstract": result}